package com.fy.fyspace.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.fyspace.common.result.PageResult;
import com.fy.fyspace.common.utils.DateFormatter;
import com.fy.fyspace.common.utils.StringTools;
import com.fy.fyspace.mapper.FileInfoMapper;
import com.fy.fyspace.mapper.FileShareMapper;
import com.fy.fyspace.model.dto.file.FileShareDTO;
import com.fy.fyspace.model.entity.FileInfo;
import com.fy.fyspace.model.entity.FileShare;
import com.fy.fyspace.model.enums.file.ExpireTimeEnum;
import com.fy.fyspace.model.vo.file.FileShareResultVO;
import com.fy.fyspace.model.vo.user.UserSessionVO;
import com.fy.fyspace.service.FileShareService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.bean.BeanUtil.copyProperties;

@Slf4j
@Service
public class FileShareServiceImpl extends ServiceImpl<FileShareMapper, FileShare> implements FileShareService {

    @Resource
    private FileInfoMapper fileInfoMapper;

    @Resource
    private FileShareMapper fileShareMapper;

    /**分享文件
     *
     * @param fileShareDTO
     * @param userSessionVO
     * @return
     */

    @Override
    @Transactional
    public FileShareResultVO fileShare(FileShareDTO fileShareDTO, UserSessionVO userSessionVO) {

        Long userId = userSessionVO.getId();
        // 创建返回对象
        FileShareResultVO shareFileResultVO = new FileShareResultVO();

        // 创建插入数据库的表对象
        FileShare fileShare = new FileShare();

        // 设置文件id
        String fileId = fileShareDTO.getFileId();
        shareFileResultVO.setFileId(fileId);
        fileShare.setFileId(fileId);

        // 设置分享id
        String shareId = userId + "Share"
                + UUID.randomUUID().toString().substring(0, 6);
        shareFileResultVO.setShareId(shareId);
        fileShare.setShareId(shareId);

        // 设置文件名字
        String fileName = fileShareDTO.getFileName();
        shareFileResultVO.setFileName(fileName);

        // 设置用户分享用户id

        shareFileResultVO.setUserId(userId);
        fileShare.setUserId(userId);

        // 设置分享时间String
        String shareTime = DateFormatter.getNowDateTimeString();
        shareFileResultVO.setShareTime(shareTime);

        // 设置分享过期时间Date
        Date expireTimeDate = ExpireTimeEnum.getExpireTimeByType(fileShareDTO.getValidType());
        fileShare.setExpireTime(expireTimeDate);

        // 设置分享时间Date
        Date shareTimeDate = new Date();
        fileShare.setShareTime(shareTimeDate);

        // 设置分享过期时间String
        String expireTime = ExpireTimeEnum.getDateStringByDays(fileShareDTO.getValidType());
        shareFileResultVO.setExpireTime(expireTime);

        // 设置分享过期具体时间类型
        Integer validType = fileShareDTO.getValidType();
        shareFileResultVO.setValidType(validType);
        fileShare.setValidType(validType);

        //获取分享文件从数据库，然后赋值所需的字段
        FileInfo fileInfo = fileInfoMapper.selectById(fileId);
        copyProperties(fileInfo,shareFileResultVO);

        // 设置分享码
        String code = fileShareDTO.getCode();
        if (StrUtil.isEmpty(code)) {
            code = StringTools.getShareCodeRandom();
        }

        shareFileResultVO.setCode(code);
        fileShare.setCode(code);

        // 插入分享信息到数据库
        fileShareMapper.insert(fileShare);

        // 返回数据
        return shareFileResultVO;
    }

    /**分享列表查询
     *
     * @param userSessionVO
     * @param pageNoString
     * @param pageSizeString
     * @return
     */

    @Override
    public PageResult fileSharePageQuery(UserSessionVO userSessionVO, String pageNoString, String pageSizeString) {
        // 检验是否为空 如果为空就表示是第一页 提供默认值
        long pageSize = pageSizeString != null && !pageSizeString.isEmpty()
                ? Long.parseLong(pageSizeString)
                : 10L;// 默认1页有10条数据
        long pageNo = pageNoString != null && !pageNoString.isEmpty()
                ? Long.parseLong(pageNoString)
                : 1L;// 默认为第1页

        Long userId=userSessionVO.getId();
        // 创建返回数据列表
        List<FileShareResultVO> fileShareResultVOList;

        // 分页查询分享列表
        IPage<FileShare> page = new Page<>(pageNo, pageSize);
        QueryWrapper<FileShare> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        // 按分享时间倒序排序
        queryWrapper.orderByDesc("shareTime");
        fileShareMapper.selectPage(page, queryWrapper);
        List<FileShare> records = page.getRecords();

        // 转换查询结果
        fileShareResultVOList = records.stream().map(record -> {
            FileShareResultVO vo = new FileShareResultVO();

            // 1. 设置分享信息
            vo.setShareId(record.getShareId());
            vo.setFileId(record.getFileId());
            vo.setUserId(record.getUserId());
            vo.setValidType(record.getValidType());
            vo.setCode(record.getCode());

            // 2. 格式化时间
            if (record.getShareTime() != null) {
                vo.setShareTime(DateFormatter.getYMDhmsFormatterStringByCST(
                        String.valueOf(record.getShareTime())));
            }
            if (record.getExpireTime() != null) {
                vo.setExpireTime(DateFormatter.getYMDhmsFormatterStringByCST(
                        String.valueOf(record.getExpireTime())));
            }

            // 判断过期时间是否在此时此刻之前，如果是代表已经过期
            if (record.getExpireTime() != null && record.getExpireTime().before(new Date())) {
                vo.setExpire(true);
            }else {
                vo.setExpire(false);
            }

            // 3. 获取文件信息
            FileInfo fileInfo = fileInfoMapper.selectById(record.getFileId());
            if (fileInfo != null) {
                copyProperties(fileInfo,vo);
                vo.setFileName(fileInfo.getFileName());
                vo.setFolderType(fileInfo.getFolderType());
                vo.setFileCategory(fileInfo.getFileCategory());
            }
            // 4. 设置浏览次数
            vo.setShowCount(record.getShowCount());

            return vo;
        }).collect(Collectors.toList());

        // 构建返回结果
        PageResult pageResult = new PageResult();
        pageResult.setTotalCount(page.getTotal());
        pageResult.setPageNo(page.getCurrent());
        pageResult.setPageSize(page.getSize());
        pageResult.setPageTotal(page.getPages());
        pageResult.setList(fileShareResultVOList);

        log.info("分享列表查询 - 总页数: {}, 当前页: {}, 每页数量: {}, 总记录数: {}",
                page.getPages(), page.getCurrent(), page.getSize(), page.getTotal());

        return pageResult;
    }

    /**
     * 取消分享
     *
     * @param fileShareIds
     */
    @Override
    public void cancelShare(String fileShareIds) {
        String[] fileShareIdsStr = fileShareIds.split(",");
        for (int i = 0; i < fileShareIdsStr.length; i++) {
            fileShareMapper.deleteById(fileShareIdsStr[i]);
        }
    }
} 